#
# openlookup/engine/signature.py
#
# Copyright 2007-2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Public-Key Signatures

See identity.py.
"""

from Crypto.Util.number import bytes_to_long, long_to_bytes
from openlookup.lib.sexp import encode, decode

class Signature(object):
    def __init__(self, type, data):
        self.type = type
        self.data = data        # tuple as defined by pycrypto

    def encode(self):
        sexp = self.export()
        return encode(sexp)

    def export(self):
        data = map(long_to_bytes, self.data)
        return [self.type] + data

def decode_signature(sexp):
    sexp = sexp if isinstance(sexp, list) else decode(sexp)
    if len(sexp) < 2 or not all(isinstance(part, str) for part in sexp):
        raise ValueError
    type, data = sexp[0], sexp[1:]
    data = tuple(map(bytes_to_long, data))
    sig = Signature(type, data)
    if sig.export() != sexp:
        raise ValueError        # Reject noncanonical encodings.
    return sig
